<template>
  <div class="home">
    <div class="full" @click="dialogVisible = true">
      <el-icon size="28" color="#1ea6f8"><FullScreen /></el-icon>
    </div>
    <div class="header"></div>
    <div class="main">
      <el-row :gutter="12">
        <el-col :xl="16" :lg="16" :md="24" :sm="24" :xs="24">
          <div class="topList">
            <div class="list">
              <div>
                <GradientText
                  :size="30"
                  :weight="600"
                  :gradient="{
                    deg: '90deg',
                    from: ' #ffd34c',
                    to: '#ffb930',
                  }"
                >
                  <NumberAnimation :to="ModbusCount" />
                </GradientText>
              </div>
              <div style="color: #fff;">Modbus事件个数</div>
            </div>
            <div class="list">
              <div>
                <GradientText
                  :size="30"
                  :weight="600"
                  :gradient="{
                    deg: '90deg',
                    from: ' #ffd34c',
                    to: '#ffb930',
                  }"
                >
                  <NumberAnimation :to="S7commCount" />
                </GradientText>
              </div>
              <div style="color: #fff;">S7事件个数</div>
            </div>
            <div class="list">
              <div>
                <GradientText
                  :size="30"
                  :weight="600"
                  :gradient="{
                    deg: '90deg',
                    from: ' #ffd34c',
                    to: '#ffb930',
                  }"
                >
                  <NumberAnimation :to="LogCount"
                /></GradientText>
              </div>
              <div style="color: #fff;">协议审计日志</div>
            </div>
            <div class="list">
              <div>
                <GradientText
                  :size="30"
                  :weight="600"
                  :gradient="{
                    deg: '90deg',
                    from: ' #ffd34c',
                    to: '#ffb930',
                  }"
                >
                  <NumberAnimation :to="AlarmCount" />
                </GradientText>
              </div>
              <div style="color: #fff;">关键事件告警数</div>
            </div>
            <div class="list">
              <div>
                <GradientText
                  :size="30"
                  :weight="600"
                  :gradient="{
                    deg: '90deg',
                    from: ' #ffd34c',
                    to: '#ffb930',
                  }"
                >
                  <NumberAnimation :to="ListCount" />
                </GradientText>
              </div>
              <div style="color: #fff;">白名单告警数</div>
            </div>
          </div>
          <div
            class="netWork"
            v-loading="loading"
          >  
          <el-image loading="lazy"  style="width: 100%; height: 100%" :src="networkTopoImage" fit="contain" />
          </div>
        </el-col>
        <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
          <div class="agreement">
            <div class="agreement_header">
              <div class="left">
                <div class="agreement_bord"></div>
                <div class="agreement_title">协议关键事件</div>
              </div>
            </div>
            <div class="agreement_content">
              <div class="agreement_top">
                <div>@timestamp</div>
                <div>source.ip</div>
                <div>destination.ip</div>
                <div>eventType</div>
                <div>protocol</div>
              </div>
              <div class="list_content">
                <el-scrollbar>
                  <div
                    class="agreement_list"
                    v-for="(item, index) in eventData"
                    :key="index"
                  >
                    <div>
                      {{ dayjs(item.eventTime).format("M月D，YYYY @HH:mm:ss") }}
                    </div>
                    <div>{{ item.sourceIp }}:{{ item.sourcePort }}</div>
                    <div>{{ item.destinationIp }}:{{ item.destinationPort }}</div>
                    <div>{{ item.eventType }}</div>
                    <div>{{ item.protocol }}</div>
                  </div>
                </el-scrollbar>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="dialogVisible" fullscreen draggable>
      <fullModal />
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import {
  getDashboardNetworkEvent,
  getDashboardNetworkTopo,
  getDashboardProtocolApp,
  getDashboardNetworkNumber,
} from "@/api/business";
import fullModal from "./fullModal.vue";
import dayjs from "dayjs";
const networkTopoImage = ref("");
const eventData = ref([]);
let timer: NodeJS.Timeout;
let timer2: NodeJS.Timeout;
let timer3: NodeJS.Timeout;
const dialogVisible = ref(false);
const loading = ref(true);
const ModbusCount = ref(0);
const S7commCount = ref(0);
const LogCount = ref(0); //日志
const ListCount = ref(0); //名单
const AlarmCount = ref(0); // 告警
async function fetchProtocolTypeData() {
  try {
    const response = await getDashboardNetworkEvent();
    eventData.value = response;
  } catch (error) {
    console.error("获取协议类型数据失败:", error);
  }
}
async function fetchDashboardNetworkTopo() {
  try {
    const imageData = await getDashboardNetworkTopo();
    if (imageData) {
      const base64Image = arrayBufferToBase64(imageData);
      networkTopoImage.value = `data:image/png;base64,${base64Image}`;
      loading.value = false;
    }
  } catch (error) {
    console.error("获取网络拓扑数据失败:", error);
  }
}
async function fetchDashboardProtocolApp() {
  try {
    const now = dayjs();
    const threeMonthsAgo = now.subtract(3, "month");
    const params = {
      startTime: threeMonthsAgo.format("YYYY-MM-DD HH:mm:ss"),
      endTime: now.format("YYYY-MM-DD HH:mm:ss"),
    };
    const response = await getDashboardProtocolApp(params);

    let modbusCount = 0;
    let s7commCount = 0;

    response.forEach((item) => {
      if (item.protocol === "MODBUS") {
        modbusCount += item.count;
      } else if (item.protocol === "S7COMM") {
        s7commCount += item.count;
      }
    });
    ModbusCount.value = modbusCount;
    S7commCount.value = s7commCount;
    console.log("MODBUS Count:", modbusCount);
    console.log("S7COMM Count:", s7commCount);
  } catch (error) {
    console.error("获取协议类型数据失败:", error);
  }
}
async function fetchNetworkData() {
  try {
    const now = dayjs();
    const threeMonthsAgo = now.subtract(3, "month");
    const params = {
      startTime: threeMonthsAgo.format("YYYY-MM-DD HH:mm:ss"),
      endTime: now.format("YYYY-MM-DD HH:mm:ss"),
    };
    let logCount = 0; //日志
    let listCount = 0; //名单
    let alarmCount = 0; // 告警
    const response = await getDashboardNetworkNumber(params);
    response.forEach((item) => {
      if (item.protocol === "协议审计日志") {
        logCount += item.count;
      } else if (item.protocol === "关键事件告警") {
        alarmCount += item.count;
      }else if (item.protocol === "白名单告警") {
        listCount += item.count;
      }
    });
    LogCount.value = logCount;
    ListCount.value = listCount;
    AlarmCount.value = alarmCount;
  } catch (error) {
    console.error("获取协议类型数据失败:", error);
  }
}
function arrayBufferToBase64(buffer: ArrayBuffer) {
  const binary = new Uint8Array(buffer);
  let base64 = "";
  const chunkSize = 8192; // 每次处理的块大小
  for (let i = 0; i < binary.length; i += chunkSize) {
    const chunk = binary.subarray(i, i + chunkSize);
    base64 += String.fromCharCode.apply(null, chunk);
  }
  return btoa(base64);
}
onMounted(async () => {
  await fetchDashboardProtocolApp();
  await fetchNetworkData();
  await fetchProtocolTypeData();
  await fetchDashboardNetworkTopo();
  timer = setInterval(fetchProtocolTypeData, 5000); // 启动定时刷新
  timer2 = setInterval(fetchNetworkData, 5000); // 启动定时刷新
  timer3 = setInterval(fetchDashboardProtocolApp, 5000);
});
onBeforeUnmount(() => {
  clearInterval(timer); // 组件销毁时清除定时器
  clearInterval(timer2); // 组件销毁时清除定时器
  clearInterval(timer3); // 组件销毁时清除定时器
});
</script>
<style lang="scss" scoped>
.home {
  background-image: url("../../assets/imgs/business/bg.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  width: 100%;
  overflow: hidden;
  height: 1120px;
  .full {
    position: relative;
    cursor: pointer;
    top: 2%;
    left: 1%;
    width: 40px;
    height: 40px;
  }
  .header {
    margin: 0 auto;
    width: 1111px;
    height: 137px;
    background-image: url("../../assets/imgs/business/header.png");
    background-size: 100% 100%;
    background-repeat: no-repeat;
  }

  .main {
    margin: 0 38px;

    .netWork {
      // background-image: url("../../assets/imgs/business/netWork.png");
      // background-size: 100% 100%;
      // background-repeat: no-repeat;
      width: 100%;
      height: 800px;
    }
    .topList {
      width: 100%;
      display: flex;
      justify-content: space-evenly;
      align-items: center;
      margin-bottom: 10px;
      .list {
        width: 186px;
        height: 110px;
        background-image: url("../../assets/imgs/business/bor.png");
        background-size: 100% 100%;
        background-repeat: no-repeat;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
      }
    }
    .agreement {
      .agreement_header {
        width: 100%;
        height: 44px;
        background-image: url("../../assets/imgs/business/group_1.png");
        background-size: 100% 100%;
        background-repeat: no-repeat;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .left {
          display: flex;
          align-items: center;
          .agreement_bord {
            margin: 0 10px;
            width: 6px;
            height: 16px;
            background: linear-gradient(0deg, #2d93ff 0%, #11b5f2 99%);
          }

          .agreement_title {
            font-size: 18px;
            color: #ffffff;
          }
        }
      }

      .agreement_content {
        width: 100%;

        .agreement_top {
          height: 40px;
          background: rgba(45, 101, 137, 0.7);
          display: flex;
          align-items: center;
          margin: 2px 0;

          div {
            flex: 1;
            text-align: center;
            font-weight: 400;
            font-size: 14px;
            color: #f2f2f2;
          }
        }
        .list_content {
          height: 830px;
          overflow: hidden;
          .agreement_list {
            height: 40px;
            background: rgba(45, 101, 137, 0.3);
            display: flex;
            align-items: center;
            margin: 2px 0;

            div {
              flex: 1;
              text-align: center;
              font-weight: 400;
              font-size: 12px;
              color: #f2f2f2;
            }
          }
        }
      }
    }
  }
}
</style>
